﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HelloOne.Store
{
    public abstract class RepositoryBase<T> : IRepository<T> 
        where T : class ,IEntity
    {
        public T Find(Guid id)
        {
            return FindSingleFast(x => x.ID == id);
        }

        public IList<T> All()
        {
            return FindMultipleFast(x => true);
        }

        public T FindSingle(Func<T, bool> func)
        {
            var result = GetEntity(func);

            if (result == null)
                throw new Exception("查询返回空序列，内部异常");
            if (result.Count > 1)
                throw new Exception("在唯一性条件中，查询到多个值");
            return result.FirstOrDefault();
        }

        public IList<T> FindMultiple(Func<T, bool> func)
        {
            var result = GetEntity(func);

            if (result == null)
                throw new Exception("查询返回空序列，内部异常");
            return result;
        }

        public T FindSingleFast(Func<T, bool> func)
        {
            var result = GetEntityFast(func);

            if (result == null)
                throw new Exception("查询返回空序列，内部异常");
            if (result.Count > 1)
                throw new Exception("在唯一性条件中，查询到多个值");
            return result.FirstOrDefault();
        }

        public IList<T> FindMultipleFast(Func<T, bool> func)
        {
            var result = GetEntityFast(func);

            if (result == null)
                throw new Exception("查询返回空序列，内部异常");
            return result;
        }

        public abstract IList<T> GetEntity(Func<T, bool> func);

        public abstract IList<T> GetEntityFast(Func<T, bool> func);

        public abstract void Save(T entity);
    }
}